# 描述: 日志工具
# 作者: 王茂林
# 时间: 2023/5/11 11:05

import time
import logging
import colorlog
from logging.handlers import RotatingFileHandler

log_level_config = {
    'debug': 10,
    'info': 20,
    'warning': 30,
    'error': 40,
    'critical': 50,
}


def get_local_time():
    """
    获取本地当前时间
    :return: 返回当前时间：2021:09:09 19:17:29
    """
    # 获取当前时间
    current_time = int(time.time())
    # 转换为localtime
    localtime = time.localtime(current_time)
    # 利用strftime()函数重新格式化时间
    return time.strftime('%Y:%m:%d %H:%M:%S', localtime)


def init_logger(level=logging.INFO, log_filename='iori-box.log'):
    """
    初始化logging配置
    :return:
    """
    # 创建logger对象
    logger = logging.getLogger()
    # 日志级别，logger 和 handler以最高级别为准，不同handler之间可以不一样，不相互影响
    logger.setLevel(level)
    # 创建控制台日志处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(level)
    # 定义颜色输出格式
    color_formatter = colorlog.ColoredFormatter(
        '%(log_color)s[%(levelname)s] %(asctime)s [%(processName)s-%(process)d-thread-%(thread)d] %(filename)s(%(lineno)d): %(message)s',
        log_colors={
            'DEBUG': 'cyan',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'bold_red',
        }
    )
    # 将颜色输出格式添加到控制台日志处理器
    console_handler.setFormatter(color_formatter)

    # 输出到文件
    # 写入文件，如果文件超过10M大小时，切割日志文件，仅保留10个文件
    file_handler = RotatingFileHandler(filename=log_filename, maxBytes=10 * 1024 * 1024, backupCount=3, encoding='utf-8')
    file_handler.setLevel(level)
    # 日志输出格式
    file_formatter = logging.Formatter(
        fmt='[%(levelname)s] %(asctime)s [%(processName)s-%(process)d-thread-%(thread)d] %(filename)s(%(lineno)d): %(message)s'
    )
    file_handler.setFormatter(file_formatter)

    # 移除默认的handler
    for handler in logger.handlers:
        logger.removeHandler(handler)
    # 将控制台日志处理器添加到logger对象
    logger.addHandler(console_handler)
    logger.addHandler(file_handler)


def debug(msg):
    """
    打印debug日志
    :param msg:
    :return:
    """
    # 解决python封装Logging模块后，log位置显示错误的问题 https://blog.csdn.net/qq_34026204/article/details/125810425
    kwargs = {"stacklevel": 2}
    logging.debug(msg, **kwargs)


def info(msg):
    """
    打印info日志
    :param msg:
    :return:
    """
    # 解决python封装Logging模块后，log位置显示错误的问题 https://blog.csdn.net/qq_34026204/article/details/125810425
    kwargs = {"stacklevel": 2}
    logging.info(msg, **kwargs)


def warning(msg):
    """
    打印warning日志
    :param msg:
    :return:
    """
    # 解决python封装Logging模块后，log位置显示错误的问题 https://blog.csdn.net/qq_34026204/article/details/125810425
    kwargs = {"stacklevel": 2}
    logging.warning(msg, **kwargs)


def critical(msg):
    """
    打印critical日志
    :param msg:
    :return:
    """
    # 解决python封装Logging模块后，log位置显示错误的问题 https://blog.csdn.net/qq_34026204/article/details/125810425
    kwargs = {"stacklevel": 2}
    logging.critical(msg, **kwargs)


def error(msg):
    """
    打印error日志,会打印堆栈信息
    :param msg:
    :return:
    """
    # 解决python封装Logging模块后，log位置显示错误的问题 https://blog.csdn.net/qq_34026204/article/details/125810425
    kwargs = {"stacklevel": 2}
    logging.error(msg, **kwargs)


def args_to_log_level(ll='debug'):
    """
    参数转为对应的日志级别，用于命令指定日志级别
    :param ll:
    :return:
    """
    # 默认info
    log_level = log_level_config['info']
    try:
        log_level = log_level_config[ll]
    except:
        pass
    return log_level
